<template>
  <div style="width: 100%;height: 100%">
    <div>
      <el-card style="width: 400px;
              height: 320px;
              margin: 250px auto;
              padding: 0 30px;
              background-color: rgba(255,255,255,0.3)">
        <!--label-width设置用户名这一列所占的宽度,如果不设置会显示在上面-->
        <h1 style="text-align: center; margin: 30px auto;">项目管理系统</h1>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0" class="demo-ruleForm">
          <el-form-item label="" prop="username">
            <el-input type="text" v-model="ruleForm.username" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item label="" prop="password">
            <el-input type="password" v-model="ruleForm.password" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
          </el-form-item>
        </el-form>
      </el-card>

    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:9878/users/login';
          console.log('url = ' + url);
          let formData = this.qs.stringify(this.ruleForm);
          console.log('formData = ' + formData);
          this.axios.post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 2000) {
              this.$message({
                message: '登录成功！',
                type: 'success'
              });
              let jwt = responseBody.data;
              console.log('登录成功，服务器端响应JWT：' + jwt);
              localStorage.setItem('jwt', jwt);
              console.log('已经将JWT保存到localStorage');
              this.$router.push('/pdms')
            } else {
              console.log(responseBody.message);
              this.$message.error(responseBody.message);
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}
</script>
